package com.itheima.travel.utils;

import com.itheima.travel.domain.Cart;
import com.itheima.travel.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
public class CartUtils {


    @Autowired
    private RedisTemplate<String,Cart> redisTemplate;


    //设置购物车到reidis中
    public void setCartToRedis(User user, Cart cart){
        redisTemplate.opsForValue().set("cart_"+user.getUsername(),cart);
    }

    //从redis中取出购物车
    public Cart getCartFromRedis(User user){
        ValueOperations<String, Cart> valueOperations = redisTemplate.opsForValue();
        //取出购物车
        Cart cart = valueOperations.get("cart_" + user.getUsername());
        //判断
        if(cart==null){
            //代表该客户reidis没有该客户的购物车，需要创建一个新的给客户
            cart = new Cart();
        }
        return cart;
    }


    //从redis中删除购物车
    public void removeCart(User user){
        redisTemplate.delete("cart_"+user.getUsername());
    }

}
